#!/bin/sh

# Copyright(c) 2011 OpenDomo Services SL. Licensed under GPL v3 or later
# Isidro Catalan <skarvin@gmail.com>


# ----------------------------------------------------------------------------
# desc: Libreria de escritura / lectura de ficheros de configuracion con 
#		formato 1:  variable="valor" o formato 2: variable valor
#
# author: Isidro Catalan <skarvin@gmail.com>, http://www.opendomo.com
# date: October 2008
#
# CHANGES:
#
# ----------------------------------------------------------------------------

# CONFIG_FORMAT = 1 --> var="value"
# CONFIG_FORMAT = 2 --> var value default
CONFIG_FORMAT="1"

setValue ()
{
 TMP_FILE="/tmp/od_$RANDOM"
 VAR_NAME="$1"
 VAR_VALUE="$2"
 mod=0
 
 if [ ! -w "$CONF_FILE" ]; then
 	/usr/bin/logger -t odvideo -p error "#ERR Unable to write on config file missing [$CONF_FILE]"
 	return
 fi
 
 while read line; do

 	found=`echo $line | grep "^$VAR_NAME"`
	 	
	 if [ -n "$found" ]; then
	 	if [ "$CONFIG_FORMAT" = "1" ]; then
	 		echo "$VAR_NAME=\"$VAR_VALUE\"" >> $TMP_FILE
	 	else
		 	echo "$VAR_NAME $VAR_VALUE" >> $TMP_FILE
		fi
	 	mod=1
	 else 
	 	echo $line >> $TMP_FILE
	 fi 
 
 done < "$CONF_FILE"
 # Si no encontramos el valor a modificar lo añadimos como
 # linea nueva 
 if [ $mod = 0 ]; then
 	if [ "$CONFIG_FORMAT" = "1" ]; then
 		echo "$VAR_NAME=\"$VAR_VALUE\"" >> $CONF_FILE
 	else
	 	echo "$VAR_NAME $VAR_VALUE" >> $CONF_FILE
	fi
 	rm $TMP_FILE 2>/dev/null
 else
	 # swapeamos los ficheros
 	mv "$TMP_FILE" "$CONF_FILE"
 fi
}

getValue ()
{
 
 VAR_NAME="$1"
 if [ ! -r "$CONF_FILE" ]; then
	/usr/bin/logger -t odvideo -p error "#ERR Unable to write on config file missing [$CONF_FILE]"
 	return
 fi
 while read line; do

	 found=`echo $line | grep "$VAR_NAME"`
	 
	 if [ -n "$found" ]; then
	 	if [ "$CONFIG_FORMAT" = "1" ]; then
			VALUE=`echo $found | cut -d"=" -f2`
		else
			VALUE=`echo $found | cut -d" " -f2-99`
		fi
		echo "$VALUE" | sed 's/\"//g'
	 fi 
	 
 done < "$CONF_FILE"

}



